﻿#include <iostream>
#include <vector>
#include <queue>
using namespace std;

class Solution
{
    int m, n;
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    bool vis[55][55];
public:
    // 675. 为高尔夫比赛砍树
    int cutOffTree(vector<vector<int>>& forest)
    {
        m = forest.size(), n = forest[0].size();
        vector<pair<int, int>> tcs;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (forest[i][j] > 1)
                    tcs.push_back({ i,j });

        sort(tcs.begin(), tcs.end(), [&](const pair<int, int> p1, const pair<int, int> p2)
            {
                return forest[p1.first][p1.second] < forest[p2.first][p2.second];
            });

        int bx = 0, by = 0, ret = 0;
        for (pair<int, int> p : tcs)
        {
            int ex = p.first, ey = p.second;
            int step = bfs(forest, bx, by, ex, ey);
            if (step == -1)
                return -1;
            ret += step;
            bx = ex, by = ey;
        }

        return ret;
    }

    int bfs(vector<vector<int>>& forest, int bx, int by, int ex, int ey)
    {
        if (bx == ex && by == ey)
            return 0;

        memset(vis, 0, sizeof(vis));
        queue<pair<int, int>> q;
        q.push({ bx, by });
        vis[bx][by] = true;
        int step = 0;

        while (q.size())
        {
            step++;
            int sz = q.size();
            while (sz--)
            {
                pair<int, int> p = q.front();
                q.pop();
                int a = p.first, b = p.second;

                for (int k = 0; k < 4; k++)
                {
                    int x = a + dx[k], y = b + dy[k];
                    if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && forest[x][y])
                    {
                        if (forest[x][y] == forest[ex][ey])
                            return step;
                        q.push({ x,y });
                        vis[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
};

int main()
{
    vector<vector<int>> v{ {1,2,3},{0,0,4},{7,6,5} };
    cout << Solution().cutOffTree(v) << endl;

    return 0;
}